<template>
  <div class="course-detail-container">
    <div class="course-container" v-loading="loading">
      <!-- 课程内容 -->
      <div v-if="course" class="course-content">
        <div class="course-header">
          <h1 class="course-title">{{ course.title }}</h1>
          <div class="course-meta">
            <span class="teacher"><i class="el-icon-s-custom"></i> 主讲：{{ course.teacher }}</span>
            <span class="category" v-if="course.categoryName">
              <i class="el-icon-collection-tag"></i> {{ course.categoryName }}
            </span>
            <span class="level" :class="'level-' + course.level">
              <i class="el-icon-medal"></i> {{ getLevelText(course.level) }}
            </span>
            <span class="duration">
              <i class="el-icon-time"></i> {{ formatDuration(course.duration) }}
            </span>
            <span class="lessons">
              <i class="el-icon-collection"></i> {{ course.lessonCount }}课时
            </span>
            <span class="likes" :class="{ 'liked': isLiked }" @click="toggleLike">
              <i :class="isLiked ? 'el-icon-star-on' : 'el-icon-star-off'"></i> {{ course.likes }}
            </span>
          </div>
        </div>

        <!-- 视频播放区域 -->
        <div class="video-container">
          <div class="video-player" v-if="currentLesson">
            <video 
              ref="videoPlayer" 
              controls 
              autoplay
              preload="auto" 
              :poster="currentLesson.cover || '/images/default-video-cover.jpg'"
              @ended="onVideoEnded">
              <source :src="currentLesson.videoUrl" type="video/mp4">
              您的浏览器不支持HTML5视频播放，请更换浏览器或更新版本。
            </video>
          </div>

          <!-- 当前视频信息 -->
          <div class="current-lesson-info" v-if="currentLesson">
            <div class="info-header">
              <h3 class="lesson-title">{{ currentLessonIndex + 1 }}. {{ currentLesson.title }}</h3>
              <div class="lesson-meta">
                <span class="views"><i class="el-icon-view"></i> {{ currentLesson.views || 0 }}</span>
                <span class="duration"><i class="el-icon-time"></i> {{ formatDuration(currentLesson.duration) }}</span>
              </div>
            </div>
            <div class="lesson-description">{{ currentLesson.description }}</div>
          </div>
        </div>

        <!-- 课程章节列表 -->
        <div class="course-tabs">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="课程章节" name="lessons">
              <div class="lessons-list">
                <div 
                  v-for="(lesson, index) in course.lessons" 
                  :key="lesson.id" 
                  class="lesson-item"
                  :class="{ 'active': currentLessonIndex === index }"
                  @click="playLesson(index)">
                  <div class="lesson-left">
                    <div class="lesson-index">{{ index + 1 }}</div>
                    <div class="lesson-info">
                      <div class="lesson-name">{{ lesson.title }}</div>
                      <div class="lesson-stats">
                        <span><i class="el-icon-time"></i> {{ formatDuration(lesson.duration) }}</span>
                        <span v-if="lesson.isFree" class="free-tag">免费</span>
                      </div>
                    </div>
                  </div>
                  <div class="lesson-status">
                    <i class="el-icon-video-play" v-if="currentLessonIndex === index"></i>
                    <i class="el-icon-lock" v-else-if="!lesson.isFree && !isPurchased"></i>
                    <span class="status-text" v-else-if="watchedLessons.includes(lesson.id)">已学习</span>
                    <span class="status-text" v-else>未学习</span>
                  </div>
                </div>
              </div>
            </el-tab-pane>

            <el-tab-pane label="课程详情" name="details">
              <div class="course-description" v-html="course.description"></div>
              
              <!-- 课程特点 -->
              <div class="course-features" v-if="course.features && course.features.length > 0">
                <h3 class="section-title">课程特点</h3>
                <ul class="features-list">
                  <li v-for="(feature, index) in course.features" :key="index">
                    <i class="el-icon-check"></i>
                    <span>{{ feature }}</span>
                  </li>
                </ul>
              </div>
              
              <!-- 适合人群 -->
              <div class="course-suitable" v-if="course.suitableFor && course.suitableFor.length > 0">
                <h3 class="section-title">适合人群</h3>
                <ul class="suitable-list">
                  <li v-for="(item, index) in course.suitableFor" :key="index">
                    <i class="el-icon-user"></i>
                    <span>{{ item }}</span>
                  </li>
                </ul>
              </div>
            </el-tab-pane>

            <el-tab-pane label="学员评价" name="comments">
              <!-- 评论区 -->
              <div class="comment-section">
                <!-- 评论表单 -->
                <div class="comment-form">
                  <el-rate v-model="ratingScore" :colors="['#99A9BF', '#F7BA2A', '#FF9900']"></el-rate>
                  <el-input
                    type="textarea"
                    :rows="4"
                    placeholder="分享你的学习感受..."
                    v-model="commentContent"
                    maxlength="500"
                    show-word-limit
                  ></el-input>
                  <div class="form-actions">
                    <el-button type="primary" :disabled="!commentContent.trim()" @click="submitComment">发表评价</el-button>
                  </div>
                </div>

                <!-- 评论列表 -->
                <div v-if="comments.length > 0" class="comment-list">
                  <div v-for="comment in comments" :key="comment.id" class="comment-item">
                    <div class="comment-avatar">
                      <img :src="comment.avatar || '/images/default-avatar.png'" :alt="comment.userName">
                    </div>
                    <div class="comment-content">
                      <div class="comment-header">
                        <span class="comment-author">{{ comment.userName }}</span>
                        <el-rate 
                          v-model="comment.rating" 
                          disabled 
                          :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                          class="comment-rating">
                        </el-rate>
                        <span class="comment-date">{{ formatDate(comment.createTime) }}</span>
                      </div>
                      <div class="comment-text">{{ comment.content }}</div>
                      <div class="comment-actions">
                        <span class="comment-like" :class="{ 'liked': comment.isLiked }" @click="toggleCommentLike(comment)">
                          <i :class="comment.isLiked ? 'el-icon-star-on' : 'el-icon-star-off'"></i>
                          <span>{{ comment.likes || 0 }}</span>
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
                
                <!-- 暂无评论 -->
                <div v-else-if="!loading" class="no-comments">
                  <i class="el-icon-chat-dot-square"></i>
                  <p>暂无评价，快来发表第一条评价吧！</p>
                </div>

                <!-- 评论分页 -->
                <div v-if="totalComments > 0" class="comment-pagination">
                  <el-pagination
                    background
                    layout="prev, pager, next"
                    :total="totalComments"
                    :page-size="commentPageSize"
                    :current-page.sync="commentPage"
                    @current-change="handleCommentPageChange">
                  </el-pagination>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>

    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/knowledge' }">知识</el-breadcrumb-item>
      <el-breadcrumb-item>{{ course.title || '课程详情' }}</el-breadcrumb-item>
    </el-breadcrumb>
  </div>
</template>

<script>
import service from '@/utils/request'

export default {
  name: 'CourseDetailVue',
  data() {
    return {
      loading: true,
      courseId: null,
      course: null,
      activeTab: 'lessons',
      currentLessonIndex: 0,
      currentLesson: null,
      isLiked: false,
      isPurchased: false,
      watchedLessons: [],
      
      // 评论相关
      comments: [],
      totalComments: 0,
      commentPage: 1,
      commentPageSize: 10,
      commentContent: '',
      ratingScore: 5
    }
  },
  created() {
    this.courseId = this.$route.params.id
    this.getCourseDetail()
    this.checkIfLiked()
    this.checkIfPurchased()
    this.getWatchedLessons()
    this.getComments()
  },
  methods: {
    // 获取课程详情
    getCourseDetail() {
      this.loading = true
      service.get(`/api/education/course/${this.courseId}`).then(res => {
        this.loading = false
        if (res.code === 200 && res.data) {
          this.course = res.data
          
          // 默认加载第一节课
          if (this.course.lessons && this.course.lessons.length > 0) {
            this.currentLesson = this.course.lessons[0]
            
            // 更新课程观看次数
            this.updateLessonViews(this.currentLesson.id)
          }
          
          document.title = `${this.course.title} - 京剧苑`
        } else {
          this.$message.error('课程不存在或已被删除')
          this.$router.push('/knowledge')
        }
      }).catch(err => {
        this.loading = false
        console.error('获取课程详情失败:', err)
        this.$message.error('获取课程详情失败，请稍后重试')
      })
    },
    
    // 播放课程
    playLesson(index) {
      if (!this.course.lessons) return
      
      const lesson = this.course.lessons[index]
      
      // 检查是否需要购买
      if (!lesson.isFree && !this.isPurchased) {
        this.$message.warning('请先购买该课程')
        return
      }
      
      this.currentLessonIndex = index
      this.currentLesson = lesson
      
      // 如果视频元素已经挂载，重新加载视频
      this.$nextTick(() => {
        if (this.$refs.videoPlayer) {
          this.$refs.videoPlayer.load()
          this.$refs.videoPlayer.play()
        }
      })
      
      // 更新观看记录
      this.updateLessonViews(lesson.id)
    },
    
    // 更新课程观看次数
    updateLessonViews(lessonId) {
      service.post(`/api/education/lesson/view/${lessonId}`).then(res => {
        if (res.code === 200) {
          // 将课程添加到已观看列表
          if (!this.watchedLessons.includes(lessonId)) {
            this.watchedLessons.push(lessonId)
          }
        }
      }).catch(err => {
        console.error('更新观看记录失败:', err)
      })
    },
    
    // 视频播放结束
    onVideoEnded() {
      // 自动播放下一节课
      if (this.currentLessonIndex < this.course.lessons.length - 1) {
        this.playLesson(this.currentLessonIndex + 1)
      }
    },
    
    // 获取已观看课程
    getWatchedLessons() {
      const token = localStorage.getItem('token')
      if (!token) return
      
      service.get(`/api/education/course/watched/${this.courseId}`).then(res => {
        if (res.code === 200 && res.data) {
          this.watchedLessons = res.data
        }
      }).catch(err => {
        console.error('获取观看记录失败:', err)
      })
    },
    
    // 检查是否已点赞
    checkIfLiked() {
      const token = localStorage.getItem('token')
      if (!token) return
      
      service.get(`/api/education/course/liked/${this.courseId}`).then(res => {
        if (res.code === 200) {
          this.isLiked = res.data
        }
      }).catch(err => {
        console.error('检查点赞状态失败:', err)
      })
    },
    
    // 检查是否已购买
    checkIfPurchased() {
      const token = localStorage.getItem('token')
      if (!token) return
      
      service.get(`/api/education/course/purchased/${this.courseId}`).then(res => {
        if (res.code === 200) {
          this.isPurchased = res.data
        }
      }).catch(err => {
        console.error('检查购买状态失败:', err)
      })
    },
    
    // 切换点赞状态
    toggleLike() {
      // 检查登录状态
      const token = localStorage.getItem('token')
      if (!token) {
        this.$message.warning('请先登录后再点赞')
        return
      }
      
      const action = this.isLiked ? 'unlike' : 'like'
      service.post(`/api/education/course/${action}/${this.courseId}`).then(res => {
        if (res.code === 200) {
          this.isLiked = !this.isLiked
          // 更新点赞数
          if (this.isLiked) {
            this.course.likes++
          } else {
            this.course.likes--
          }
          this.$message.success(this.isLiked ? '点赞成功' : '取消点赞成功')
        }
      }).catch(err => {
        console.error('操作点赞失败:', err)
        this.$message.error('操作失败，请稍后重试')
      })
    },
    
    // 获取评论
    getComments() {
      service.get(`/api/education/course/comments/${this.courseId}`, {
        params: {
          page: this.commentPage,
          pageSize: this.commentPageSize
        }
      }).then(res => {
        if (res.code === 200 && res.data) {
          this.comments = res.data.list || []
          this.totalComments = res.data.total || 0
        }
      }).catch(err => {
        console.error('获取评论失败:', err)
        this.$message.error('获取评论失败，请稍后重试')
      })
    },
    
    // 评论分页
    handleCommentPageChange(page) {
      this.commentPage = page
      this.getComments()
    },
    
    // 提交评论
    submitComment() {
      // 检查登录状态
      const token = localStorage.getItem('token')
      if (!token) {
        this.$message.warning('请先登录后再评价')
        return
      }
      
      if (!this.commentContent.trim()) {
        this.$message.warning('评价内容不能为空')
        return
      }
      
      const comment = {
        courseId: this.courseId,
        content: this.commentContent.trim(),
        rating: this.ratingScore
      }
      
      service.post('/api/education/course/comment', comment).then(res => {
        if (res.code === 200) {
          this.$message.success('评价成功')
          this.commentContent = ''
          this.ratingScore = 5
          // 重新加载评论
          this.commentPage = 1
          this.getComments()
        }
      }).catch(err => {
        console.error('提交评价失败:', err)
        this.$message.error('评价失败，请稍后重试')
      })
    },
    
    // 点赞评论
    toggleCommentLike(comment) {
      // 检查登录状态
      const token = localStorage.getItem('token')
      if (!token) {
        this.$message.warning('请先登录后再点赞')
        return
      }
      
      const action = comment.isLiked ? 'unlike' : 'like'
      service.post(`/api/education/comment/${action}/${comment.id}`).then(res => {
        if (res.code === 200) {
          comment.isLiked = !comment.isLiked
          // 更新点赞数
          if (comment.isLiked) {
            comment.likes = (comment.likes || 0) + 1
          } else {
            comment.likes = Math.max(0, (comment.likes || 0) - 1)
          }
        }
      }).catch(err => {
        console.error('操作评论点赞失败:', err)
        this.$message.error('操作失败，请稍后重试')
      })
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '未知日期'
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
    },
    
    // 格式化课程时长
    formatDuration(minutes) {
      if (!minutes) return '未知时长'
      const hours = Math.floor(minutes / 60)
      const mins = minutes % 60
      return hours > 0 ? `${hours}小时${mins > 0 ? mins + '分钟' : ''}` : `${mins}分钟`
    },
    
    // 获取难度等级文本
    getLevelText(level) {
      const levelMap = {
        'beginner': '初级',
        'intermediate': '中级',
        'advanced': '高级'
      }
      return levelMap[level] || '未知'
    },

    // 返回课程列表
    goBack() {
      this.$router.push('/knowledge');
    }
  }
}
</script>

<style scoped>
.course-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  padding-top: 80px;
}

.course-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.course-header {
  margin-bottom: 30px;
}

.course-title {
  font-size: 1.8rem;
  color: #8B0000;
  margin-top: 0;
  margin-bottom: 15px;
  font-family: 'STXingkai', 'STZhongsong', serif;
}

.course-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.course-meta span {
  font-size: 0.9rem;
  color: #666;
  display: flex;
  align-items: center;
}

.course-meta i {
  margin-right: 5px;
}

.level {
  padding: 2px 8px;
  border-radius: 4px;
  color: white;
}

.level-beginner {
  background-color: #4CAF50;
}

.level-intermediate {
  background-color: #FF9800;
}

.level-advanced {
  background-color: #F44336;
}

.likes {
  cursor: pointer;
  transition: all 0.3s ease;
}

.likes:hover {
  color: #FFD700;
}

.likes.liked {
  color: #FFD700;
}

/* 视频播放器 */
.video-container {
  margin-bottom: 30px;
  background-color: #f5f5f5;
  border-radius: 8px;
  overflow: hidden;
}

.video-player {
  position: relative;
  padding-top: 56.25%; /* 16:9 比例 */
  overflow: hidden;
  background-color: #000;
}

.video-player video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.current-lesson-info {
  padding: 20px;
}

.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  flex-wrap: wrap;
}

.lesson-title {
  margin: 0;
  font-size: 1.3rem;
  color: #333;
}

.lesson-meta {
  display: flex;
  gap: 15px;
  color: #666;
  font-size: 0.9rem;
}

.lesson-description {
  color: #666;
  line-height: 1.6;
}

/* 课程章节 */
.lessons-list {
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
}

.lesson-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: all 0.3s ease;
}

.lesson-item:last-child {
  border-bottom: none;
}

.lesson-item:hover {
  background-color: #f9f9f9;
}

.lesson-item.active {
  background-color: #f0f9ff;
  border-left: 4px solid #8B0000;
}

.lesson-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.lesson-index {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #8B0000;
  color: white;
  border-radius: 50%;
  font-weight: bold;
}

.lesson-info {
  display: flex;
  flex-direction: column;
}

.lesson-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 5px;
}

.lesson-stats {
  display: flex;
  gap: 10px;
  font-size: 0.8rem;
  color: #999;
}

.free-tag {
  color: #4CAF50;
  font-weight: bold;
}

.lesson-status {
  color: #999;
  font-size: 0.9rem;
}

.el-icon-lock {
  color: #F44336;
}

.el-icon-video-play {
  color: #8B0000;
  font-size: 1.2rem;
}

/* 详情 */
.course-description {
  line-height: 1.8;
  color: #333;
  margin-bottom: 30px;
}

.section-title {
  color: #8B0000;
  font-size: 1.3rem;
  margin-bottom: 15px;
  font-weight: bold;
  position: relative;
  padding-left: 15px;
}

.section-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 5px;
  height: 20px;
  background-color: #8B0000;
  border-radius: 2px;
}

.features-list, .suitable-list {
  padding-left: 20px;
  list-style-type: none;
}

.features-list li, .suitable-list li {
  margin-bottom: 10px;
  display: flex;
  align-items: flex-start;
}

.features-list i, .suitable-list i {
  color: #8B0000;
  margin-right: 10px;
  font-size: 1.1rem;
}

/* 评论样式 */
.comment-form {
  margin-bottom: 30px;
}

.form-actions {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.comment-list {
  margin-top: 20px;
}

.comment-item {
  display: flex;
  padding: 20px 0;
  border-bottom: 1px solid #eee;
}

.comment-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
  margin-right: 15px;
}

.comment-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.comment-content {
  flex-grow: 1;
}

.comment-header {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.comment-author {
  font-weight: bold;
  color: #333;
}

.comment-rating {
  margin: 0 10px;
}

.comment-date {
  color: #999;
  font-size: 0.8rem;
}

.comment-text {
  line-height: 1.6;
  color: #333;
  margin-bottom: 10px;
  word-break: break-word;
}

.comment-actions {
  display: flex;
  gap: 15px;
}

.comment-like {
  color: #999;
  font-size: 0.9rem;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.comment-like i {
  margin-right: 5px;
}

.comment-like.liked {
  color: #FFD700;
}

.comment-like:hover {
  color: #8B0000;
}

.no-comments {
  text-align: center;
  padding: 30px;
  color: #999;
}

.no-comments i {
  font-size: 3rem;
  margin-bottom: 10px;
}

.comment-pagination {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .course-detail-container {
    padding: 10px;
    padding-top: 70px;
  }
  
  .course-container {
    padding: 20px;
  }
  
  .course-title {
    font-size: 1.5rem;
  }
  
  .course-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .info-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .comment-avatar {
    width: 40px;
    height: 40px;
  }
}

@media (max-width: 480px) {
  .course-container {
    padding: 15px;
  }
  
  .course-title {
    font-size: 1.3rem;
  }
  
  .lesson-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .lesson-status {
    margin-top: 10px;
    align-self: flex-end;
  }
}
</style> 